package com.ikingtech.platform.service.system.role.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.component.api.CompRoleApi;
import com.ikingtech.framework.sdk.component.model.ComponentRole;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.enums.common.ElementTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.role.entity.RoleDO;
import com.ikingtech.platform.service.system.role.service.repository.RoleRepository;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public abstract class AbstractCompRoleService implements CompRoleApi {

    private final RoleRepository repo;

    /**
     * 根据名称查询角色列表
     *
     * @param name 角色名称
     * @return 角色列表
     */
    @Override
    public List<ComponentRole> listByName(String name) {
        return this.convert(this.repo.list(Wrappers.<RoleDO>lambdaQuery()
                // 根据角色名称模糊查询
                .like(RoleDO::getName, name)
                // 根据域代码查询
                .eq(Tools.Str.isNotBlank(Me.domainCode()), RoleDO::getDomainCode, Me.domainCode())
                // 根据租户代码查询
                .eq(Tools.Str.isNotBlank(Me.tenantCode()), RoleDO::getTenantCode, Me.tenantCode())
                // 根据应用代码查询
                .eq(Tools.Str.isNotBlank(Me.appCode()), RoleDO::getAppCode, Me.appCode())));
    }

    private List<ComponentRole> convert(List<RoleDO> roles) {
        return Tools.Coll.convertList(roles, role -> {
            ComponentRole compRole = new ComponentRole();
            compRole.setElementId(role.getId());
            compRole.setElementName(role.getName());
            compRole.setElementType(ElementTypeEnum.ROLE);
            compRole.setTenantCode(role.getTenantCode());
            return compRole;
        });
    }
}
